package com.yyk.yykywd.ui.home.fragment;

import android.graphics.Color;
import android.os.Bundle;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.github.mikephil.charting.charts.HorizontalBarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.orhanobut.logger.Logger;
import com.yyk.yykywd.R;
import com.yyk.yykywd.aa.HorinalBarChartManager;
import com.yyk.yykywd.aa.PieChartBean;
import com.yyk.yykywd.aa.PieChartManager;
import com.yyk.yykywd.base.BaseFragment;
import com.yyk.yykywd.base.BaseRecyclerAdapter;
import com.yyk.yykywd.base.BaseRecyclerHolder;
import com.yyk.yykywd.http.ApiService;
import com.yyk.yykywd.bean.IndexIndexallInfo;
import com.yyk.yykywd.bean.IndexLinelistInfo;
import com.yyk.yykywd.ui.DongtaibobaoActivity;
import com.yyk.yykywd.util.Md5Util2;
import com.yyk.yykywd.util.OnClickFlagUtil;
import com.yyk.yykywd.util.ToastUtil;
import com.yyk.yykywd.widght.diver.CustomDecoration;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 首页 业务线fragment
 */

public class BusinessLinesFragment extends BaseFragment {

    public static BusinessLinesFragment intanse;
    public static final String ARGS_PAGE = "BusinessLinesFragment";
    @BindView(R.id.rv_report)
    RecyclerView rvReport;
    @BindView(R.id.ll_emptyreport)
    LinearLayout llEmptyreport;

    @BindView(R.id.tv_btdtbbmore)
    TextView tvBtdtbbmore;

    //客户统计

    @BindView(R.id.tv_jihua)
    TextView tvJihua;  //计划
    //待签合同
    @BindView(R.id.tv_dq)
    TextView tvDq;

    @BindView(R.id.tv_dh)  //待回款
            TextView tvDh;

    @BindView(R.id.tv_hz)    //合作成功
            TextView tvHz;
    @BindView(R.id.tv_zw)    //暂未达成

            TextView tvZw;

    @BindView(R.id.piechart)  //饼图
            PieChart piechart;
    @BindView(R.id.horizontbarchart)  // 好的柱形图
            HorizontalBarChart horizontalBarChart;
    @BindView(R.id.tv_starttime)
    TextView tvStarttime;
    @BindView(R.id.tv_endtime)
    TextView tvEndtime;
    @BindView(R.id.ll_timehide) //时间筛选框 显示
            LinearLayout llTimehide;
    @BindView(R.id.ll_quanbuhide) //全部显示
            LinearLayout llQuanbuhide;
    @BindView(R.id.ll_yejihide) //业绩统计
            LinearLayout llYejihide;
    @BindView(R.id.ll_emptyview)//占位图
            LinearLayout llEmptyview;
    @BindView(R.id.ns_view)//数据图
            NestedScrollView nsView;
    private String id; //传过来的ID值
    private List<IndexLinelistInfo.ReportBean> reportList = new ArrayList<>(); //
    private List<IndexLinelistInfo.StudycountBean> studycount = new ArrayList<>();

    private BaseRecyclerAdapter<IndexLinelistInfo.ReportBean> adapter;

    List<IndexIndexallInfo.ReportallBean> reportAllList = new ArrayList<>();//全部的动态播报
    private BaseRecyclerAdapter<IndexIndexallInfo.ReportallBean> adapter2;


    private PieChartManager pieChartManager; //客户统计
    private HorinalBarChartManager horinalBarChartManager;//业绩统计

    List<PieChartBean> pieList = new ArrayList<>(); //筛选集合
    List<Integer> integers = new ArrayList<>();
    private int pageIndex = 1;//默认页数是1

    private long time2 = 200; //默认
    private long time = 100;


    public static BusinessLinesFragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARGS_PAGE, page);
        BusinessLinesFragment fragment = new BusinessLinesFragment();
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (up) {
            //TODO 在这里处理数据
            if (id.equals("0")) {
                postIndexIndexall(true);
            } else if (id.equals("6")) {
                //经营业务线不需要任何网络请求，暂时还没有这个业务
            } else {
                postIndexLinelist(true);
                postIndexLinelist2(true);
            }
            up = false;//刷新一次即可，不需要一直刷新
        }
//        ToastUtil.showShort("展示");
    }

    private boolean up = false;

    @Override
    public void onPause() {
        super.onPause();
        up = true;
        Logger.e("周康——暂停");
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        super.onFragmentVisibleChange(isVisible);
        if (isVisible) {
            //TODO 在这里处理数据
            if (id.equals("0")) {
                postIndexIndexall(true);
            } else if (id.equals("6")) {
                //经营业务线不需要任何网络请求，暂时还没有这个业务
            } else {
                postIndexLinelist(true);
                postIndexLinelist2(true);
            }
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_businesslines;
    }

    @Override
    public void initView() {
        iniTime();
        initChart();
    }

    /**
     * 时间日期
     */
    private void iniTime() {
//1.
        SimpleDateFormat dateFormater = new SimpleDateFormat(
                "yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.getTime();

        //2.
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());


        try {
            tvStarttime.setText(URLEncoder.encode(dateFormater.format(cal.getTime()), "UTF-8"));
            tvEndtime.setText(URLEncoder.encode(simpleDateFormat.format(date), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


    }


    private void initChart() {
        //饼形图
        pieChartManager = new PieChartManager(getActivity(), piechart);
        horinalBarChartManager = new HorinalBarChartManager(getActivity(), horizontalBarChart);
    }

    @Override
    public void initData() {
        intanse = this;
        Bundle arguments = getArguments();
        id = arguments.getString(BusinessLinesFragment.ARGS_PAGE);
        Logger.e("type——————" + id);
        //这里判断是全部 还是其余页面布局
        if (id.equals("0")) {
            llTimehide.setVisibility(View.GONE);
            llQuanbuhide.setVisibility(View.VISIBLE);
            llYejihide.setVisibility(View.GONE);
        } else if (id.equals("6")) {
            llEmptyview.setVisibility(View.VISIBLE);
            nsView.setVisibility(View.GONE);
        }
        //TODO 在这里处理数据
        if (id.equals("0")) {
            postIndexIndexall(true);
        } else if (id.equals("6")) {
            //经营业务线不需要任何网络请求，暂时还没有这个业务
        } else {
            postIndexLinelist(true);
            postIndexLinelist2(true);
        }
        initAdapter();

    }


    /**
     * TODO接口25.工作模块首页（ggk）  要改接口参数
     * 1.控制动态播报
     */
    public void postIndexLinelist(final boolean flag) {

        Map<String, String> map = new TreeMap<>();
        map.put("id", id);
        map.put("page", "1");
        map.put("num", "4");
        map.put("opentime", tvStarttime.getText().toString().trim());
        map.put("shuttime", tvEndtime.getText().toString().trim());
        map.put("sign", Md5Util2.createSign(map));
        ApiService.getInstance().api.postIndexLinelist(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Observer<IndexLinelistInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(IndexLinelistInfo info) {
                        Logger.e("工作模块首页 动态播报" + info.toString());
                        if (info.getCode() == 1) {
                            if (flag) {
                                reportList.clear();
                            }
                            if (info.getReport() != null && info.getReport().size() > 0) {
                                //动态播报
                                reportList.addAll(info.getReport());
                                llEmptyreport.setVisibility(View.GONE);
                                rvReport.setVisibility(View.VISIBLE);
                            } else {
                                llEmptyreport.setVisibility(View.VISIBLE);
                                rvReport.setVisibility(View.GONE);

                            }
                            adapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.t("异常" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 2.控制客户统计 可以合成一个貌似
     *
     * @param flag
     */
    public void postIndexLinelist2(final boolean flag) {
        // 保留前六位
        if (time > time2) {
            Logger.d(time + "对比" + time2);
            ToastUtil.showShort("时间格式不对");
            return;
        }
        Map<String, String> map = new TreeMap<>();
        map.put("id", id);
        map.put("page", "1");
        map.put("num", "4");
        map.put("opentime", tvStarttime.getText().toString().trim());
        map.put("shuttime", tvEndtime.getText().toString().trim());
        map.put("sign", Md5Util2.createSign(map));
        ApiService.getInstance().api.postIndexLinelist(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Observer<IndexLinelistInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(IndexLinelistInfo info) {
                        Logger.e("工作模块首页 表格图" + info.toString());
                        if (info.getCode() == 1) {
                            //1.客户统计
                            //如果为true，清楚掉之前加的数据
                            if (flag) {
                                pieList.clear();
                                integers.clear();
                                studycount.clear();
                            }
                            IndexLinelistInfo.ClientcountBean clientcount = info.getClientcount();
                            int jihua = clientcount.getJihua();
                            int daiqian = clientcount.getDaiqian();
                            int huikuan = clientcount.getHuikuan();
                            int chenggong = clientcount.getChenggong();
                            int zanwei = clientcount.getZanwei();
                            int sum = clientcount.getSum();

                            pieList.add(new PieChartBean(Float.valueOf(jihua), "业务计划"));
                            pieList.add(new PieChartBean(Float.valueOf(daiqian), "待签合同"));
                            pieList.add(new PieChartBean(Float.valueOf(huikuan), "待回款"));
                            pieList.add(new PieChartBean(Float.valueOf(chenggong), "合作成功"));
                            pieList.add(new PieChartBean(Float.valueOf(zanwei), "暂未合作"));
                            integers.add(0XFF5276D6);
                            integers.add(0XFF49B282);
                            integers.add(0XFFEA524A);
                            integers.add(0XFF388A9F);
                            integers.add(0XFFFA8440);
                            Logger.d("业务线" + pieList.size());
                            pieChartManager.setData(pieList, integers, sum + "\n总客户");
                            tvJihua.setText("业务计划：" + jihua);
                            tvDq.setText("待签合同：" + daiqian);
                            tvDh.setText("待回款：" + huikuan);
                            tvHz.setText("合作成功：" + chenggong);
                            tvZw.setText("暂未合作：" + zanwei);


                            //2.业绩统计
                            if (info.getStudycount() != null && info.getStudycount().size() > 0) {
                                studycount.addAll(info.getStudycount());
                                Logger.e("业绩统计" + studycount.size());
                            }
                            horinalBarChartManager.initData(studycount);

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.t("异常" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 接口34.首页全部（ggk）
     *
     * @param flag
     */
    public void postIndexIndexall(final boolean flag) {
        Map<String, String> map = new TreeMap<>();
        map.put("page", pageIndex + "");
        map.put("num", "4");
        map.put("sign", Md5Util2.createSign(map));
        ApiService.getInstance().api.postIndexIndexall(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Observer<IndexIndexallInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(IndexIndexallInfo info) {
                        Logger.e("首页全部（ggk）" + info.toString());
                        if (info.getCode() == 1) {

                            //如果为true，清楚掉之前加的数据
                            if (flag) {
                                pieList.clear();
                                integers.clear();
                                reportAllList.clear();
                            }
                            //1.播报
                            if (info.getReportall() != null && info.getReportall().size() > 0) {
                                //动态播报
                                reportAllList.addAll(info.getReportall());
                                llEmptyreport.setVisibility(View.GONE);
                                rvReport.setVisibility(View.VISIBLE);
                            } else {
                                llEmptyreport.setVisibility(View.VISIBLE);
                                rvReport.setVisibility(View.GONE);

                            }
                            adapter2.notifyDataSetChanged();
                            //2.客户统计
                            List<IndexIndexallInfo.XianallBean> clientcount = info.getXianall();

                            for (int i = 0; i < clientcount.size(); i++) {
                                pieList.add(new PieChartBean(clientcount.get(i).getValue(), clientcount.get(i).getName()));
                            }
                            integers.add(0XFF5276D6);
                            integers.add(0XFF49B282);
                            integers.add(0XFFEA524A);
                            integers.add(0XFF388A9F);
                            integers.add(0XFFFA8440);
                            pieChartManager.setData(pieList, integers, clientcount.get(0).getSum() + "\n总客户");
                            tvJihua.setText(clientcount.get(0).getName() + ":" + clientcount.get(0).getValue());
                            tvDq.setText(clientcount.get(1).getName() + ":" + clientcount.get(1).getValue());
                            tvDh.setText(clientcount.get(2).getName() + ":" + clientcount.get(2).getValue());
                            tvHz.setText(clientcount.get(3).getName() + ":" + clientcount.get(3).getValue());
                            tvZw.setText(clientcount.get(4).getName() + ":" + clientcount.get(4).getValue());


                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.t("异常" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initAdapter() {
        if (id.equals("0")) {
            adapter2 = new BaseRecyclerAdapter<IndexIndexallInfo.ReportallBean>(getActivity(), reportAllList, R.layout.adapter_item_businesslines_f) {
                @Override
                public void convert(BaseRecyclerHolder holder, IndexIndexallInfo.ReportallBean item, int position, boolean isScrolling) {
                    holder.setText(R.id.tv_state, item.getTopname() + "     " + item.getState());
                    holder.setText(R.id.tv_createtime, item.getCreatetime());
                }
            };
            rvReport.addItemDecoration(new CustomDecoration(getActivity(), CustomDecoration.VERTICAL_LIST, R.drawable.divider_e5_05, 0));
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            rvReport.setLayoutManager(linearLayoutManager);
            rvReport.setAdapter(adapter2);
            adapter2.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView parent, View view, int position) {
//                Bundle bundle = new Bundle();
//                bundle.putString("id", reportList.get(position).getState() + "");
////                startAct(BusinessPlan2Activity.class, bundle);

                }
            });

        } else {
            adapter = new BaseRecyclerAdapter<IndexLinelistInfo.ReportBean>(getActivity(), reportList, R.layout.adapter_item_businesslines_f) {
                @Override
                public void convert(BaseRecyclerHolder holder, IndexLinelistInfo.ReportBean item, int position, boolean isScrolling) {
                    holder.setText(R.id.tv_createtime, item.getCreatetime());
                    holder.setText(R.id.tv_state, item.getState());

                }
            };
            rvReport.addItemDecoration(new CustomDecoration(getActivity(), CustomDecoration.VERTICAL_LIST, R.drawable.divider_e5_05, 0));
            rvReport.setLayoutManager(new LinearLayoutManager(getActivity()));
            rvReport.setAdapter(adapter);
            adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView parent, View view, int position) {
//                Bundle bundle = new Bundle();
//                bundle.putString("id", reportList.get(position).getState() + "");
////                startAct(BusinessPlan2Activity.class, bundle);

                }
            });
        }

    }


    /**
     * 1.开始时间
     * 2.结束时间
     * 3.动态播报更多
     * 4.筛选日期
     *
     * @param view
     */
    @OnClick({R.id.tv_starttime, R.id.tv_endtime, R.id.ll_btdtbbmore, R.id.tv_shaixuan})
    public void onViewClicked(View view) {
        if (OnClickFlagUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_starttime:
                //时间选择器
                TimePickerView pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        tvStarttime.setText(getTime(date));
                        //开始时间
                        time = date.getTime() / 1000;
                    }
                }).setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                        .setTitleText("选择日期")
                        .setSubmitText("确定")//确定按钮文字
                        .setSubCalSize(15)
                        .setSubmitColor(0xff212121) //确定文字颜色
                        .setCancelText("取消 ")//取消按钮文字
                        .setSubCalSize(15)
                        .setCancelColor(0xff777777)//取消文字颜色
                        .setDividerColor(0xffD7D7D7) //分割线颜色
                        .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                        .setContentTextSize(15)
                        .setLineSpacingMultiplier(2.5f) // item 间距
                        .build();
                pvTime.show(tvStarttime);
                tvStarttime.setTextColor(getResources().getColor(R.color.blue_41));
                break;
            case R.id.tv_endtime:
                //时间选择器
                TimePickerView pvTime2 = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        tvEndtime.setText(getTime(date));
                        //结束时间
                        time2 = date.getTime() / 1000;
                    }
                }).setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                        .setTitleText("选择日期")
                        .setSubmitText("确定")//确定按钮文字
                        .setSubCalSize(15)
                        .setSubmitColor(0xff212121) //确定文字颜色
                        .setCancelText("取消 ")//取消按钮文字
                        .setSubCalSize(15)
                        .setCancelColor(0xff777777)//取消文字颜色
                        .setDividerColor(0xffD7D7D7) //分割线颜色
                        .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                        .setContentTextSize(15)
                        .setLineSpacingMultiplier(2.5f) // item 间距
                        .build();
                pvTime2.show(tvEndtime);
                tvEndtime.setTextColor(getResources().getColor(R.color.blue_41));
                break;
            case R.id.ll_btdtbbmore:
                Bundle bundle = new Bundle();
                bundle.putString("id", id);
                startAct(DongtaibobaoActivity.class, bundle);
                break;
            case R.id.tv_shaixuan:
                postIndexLinelist2(true);
                break;
        }
    }


    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


}